# constructProj/jsonConfig.py
# -*-coding:utf-8 -*-
# @file       jsonConfig.py
# @author     yearnext
# @version    1.0.0
# @date       2021-11-19
# @brief      constructProj jsonConfig.py component
import os
import sys
import traceback
import re
from PyQt5 import QtCore, QtGui, QtWidgets
from moudles.ui.SerialSend import uiSerialSend
from moudles.tool.tLog import *


class SerialSendWidget(QtWidgets.QWidget, uiSerialSend):
    sigSend = pyqtSignal(int, int, list)
    # sigClose = pyqtSignal(str)

    def __init__(self, argv, parent=None):
        super().__init__(parent)

        # UI初始化
        self.uiInit()

        # 输入参数初始化
        self.inputParamInit(argv)

        # 信号槽初始化
        self.signalSoltInit()

    # UI初始化
    def uiInit(self):
        # UI 初始化
        self.setupUi(self)

    # 输入参数初始化
    def inputParamInit(self, argv):
        tLog.putFuncArg(argv)

    def signalSoltInit(self):
        print('signal solt init')

        self.sendButton.clicked.connect(self.sendProcess)
        # self.sendTextEdit.textChanged.connect(self.sendProcess)

    def char2num(self, ch):
        if '0' <= ch <= '9':
            val = int(ord(ch) - ord('0'))
        elif 'a' <= ch <= 'f':
            val = int(ord(ch) - ord('a') + 10)
        elif 'A' <= ch <= 'F':
            val = int(ord(ch) - ord('A') + 10)
        elif ch == ' ':
            val = int(-1)
        else:
            val = int(-2)

        # print(ch, val)

        return val

    def str2hexData(self, param:list, order:int=0):
        ins = 0
        high = 0
        low = 0
        hexData = []

        for i in param:
            if ins == 0:
                high = self.char2num(i)

                if high == -2:
                    high = int(0)

                if high != -1:
                    ins = 1
            else:
                low = self.char2num(i)

                # 整理high bit以及low bit
                if high == -2 and low == -2:
                    continue
                # low == ' '
                elif low == -1:
                    low = int(0)
                    # high == invalid
                    if high == -2:
                        ins = 0
                        continue
                # low == invalid
                elif low == -2:
                    low = int(0)
                    # high == invalid
                    if high == -2:
                        ins = 0
                        continue
                else:
                    high = int(high * 16)

                val = int(high + low)
                if order == 0:
                    hexData.append(val.to_bytes(1, byteorder='little', signed=False))
                else:
                    hexData.append(val.to_bytes(1, byteorder='big', signed=False))

                ins = 0

        if ins == 1:
            if high is not None:
                hexData.append(high)

        return  hexData

    def getSendData(self):
        sendText = self.sendTextEdit.toPlainText()

        if len(sendText) == 0:
            return []

        sendData = list(sendText)
        # print('SendData:', sendData)

        # 字符串模式处理
        if self.hexModeCheckBox.isChecked() == False:
            if self.addCarriageCheckBox.isChecked() == True:
                sendData.append('\r')
                sendData.append('\n')

            return sendData

        # HEX模式处理
        sendData = self.str2hexData(sendData)
        return sendData

    def sendProcess(self):
        sendData = self.getSendData()

        if len(sendData) == 0:
            return

        print(type(sendData), sendData)
        self.sigSend.emit(0, 0, sendData)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    window = SerialSendWidget(sys.argv)
    window.show()
    sys.exit(app.exec_())
